package com.example.lenovo.asia5b.home.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.example.lenovo.asia5b.commodity.activity.CommodityDetActivity;
import com.example.lenovo.asia5b.util.InterceptUrl;
import com.wushi.lenovo.asia5b.R;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import app.BaseActivity;


/**
 * Created by lenovo on 2017/6/29.
 */

public class WebViewActivity extends BaseActivity{

    private WebView webView;
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        initView();
    }

    private void initView(){
        dialog = new ProgressDialog(WebViewActivity.this);;//加载提示
        Window window = dialog.getWindow();
        WindowManager.LayoutParams windowManager = window.getAttributes();
        windowManager.alpha = 0.7f;// 透明度
        windowManager.dimAmount = 0.8f;// 黑暗度

        webView = (WebView)findViewById(R.id.activity_webview);
        WebSettings settings = webView.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(true);//支持缩放
        settings.setBuiltInZoomControls(true);//启用内置缩放装置
//        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//缓存
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//可能的话使所有列的宽度不超过屏幕宽度
        settings.setUseWideViewPort(true);//设置webview推荐使用的窗口
        settings.setLoadWithOverviewMode(true);//设置加载进来的页面自适应手机屏幕
        settings.setSavePassword(true);
        settings.setSaveFormData(true);
        settings.setGeolocationEnabled(true);
        settings.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");
        // enable Web Storage: localStorage, sessionStorage
        //屏蔽的话，能阻止天猫弹出框，但是 也会导致显示不出天猫国际菜单栏和 拼多多里面商品的无法点击
        settings.setDomStorageEnabled(true);
        settings.setBlockNetworkImage(false);
        //为什么要加这句，http://blog.csdn.net/u013320868/article/details/52837671 访问这个就可以了
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.requestFocus();
        webView.setScrollBarStyle(0);

        String url = "";
        String tagerName = "";
        Intent intent = this.getIntent();
        //根据名站推荐在webview打开对应的连接
        if(intent.hasExtra("url")) {
            url = intent.getStringExtra("url");//天猫
        }
        webView.loadUrl(url);
        webView.setWebViewClient(new A5bWebViewClient());
        if (getIntent().hasExtra("san")) {
            F.id(R.id.public_title_name).text(getResources().getString(R.string.dsfsc));
        } else {
            F.id(R.id.public_title_name).text(getResources().getString(R.string.details));
            if (url.indexOf("/activity.php?act=type&a=a")>-1) {
//                settings.setJavaScriptEnabled(true);
            } else {
//                settings.setJavaScriptEnabled(true);
            }
        }
        if (getIntent().hasExtra("bzzx")){
            F.id(R.id.public_title_name).text(getResources().getString(R.string.bzzx));
        }
        F.id(R.id.public_btn_left).clicked(this);

        if (getIntent().hasExtra("promotionTitle")){
            F.id(R.id.public_title_name).text(intent.getStringExtra("promotionTitle"));
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }else{
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void interceptUrl(String url){
        Intent intent = new Intent(WebViewActivity.this, CommodityDetActivity.class);
        intent.putExtra("tmall",url);
        startActivity(intent);
    }

    private void activityUrl(String goodsid){
        Intent intent = new Intent(WebViewActivity.this, CommodityDetActivity.class);
        intent.putExtra("goods_id",goodsid);
        startActivity(intent);
    }

    /**
     * 重写WebViewClient
     */
    private class A5bWebViewClient extends WebViewClient{
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            Log.e("===========URL========",url);

            //活动的banner图跳转到详情的链接
            if (getIntent().hasExtra("promotionTitle")){
                if (url.indexOf(InterceptUrl.OurLink) > -1){
                    int indexStart = url.indexOf("id=");
                    String actStr = url.substring(indexStart+3);
                    activityUrl(actStr);
                    return true;
                }
            }

            //WebView拦截掉特殊的协议
            if(url.startsWith("tmall:") || url.startsWith("taobao:") || url.startsWith("openapp.jdmobile:")
                || url.startsWith("mogujie:") || url.startsWith("jsbridge:")
                ||url.startsWith("mobile.yangkeduo.com/login.html")) {

                return true;
            }//
            if (isTaobaoThree(url)){
                view.loadUrl(url);
                return true;
            }
            if (url.indexOf("m.asia5b.com/goods.php?id")>-1) {
                interceptUrl(url);
                return true;
            }

//            if (url.indexOf(InterceptUrl.TAOBAO_FIVE) > -1){
//                interceptUrl(url);
//                return true;
//            }

            if(url.indexOf(InterceptUrl.TMALL_ONE) > -1 || url.indexOf(InterceptUrl.TMALL_TWO) > -1
                    || url.indexOf(InterceptUrl.TAOBAO_ONE) > -1 || url.indexOf(InterceptUrl.TAOBAO_TWO) > -1
                    || url.indexOf(InterceptUrl.JD_ONE) > -1 || url.indexOf(InterceptUrl.JD_TWO) > -1
                    || url.indexOf(InterceptUrl.MOGUJIE_ONE) > -1 || url.indexOf(InterceptUrl.MOGUJIE_TWO) > -1
                    || url.indexOf(InterceptUrl.MOGUJIE_THREE) > -1 || url.indexOf(InterceptUrl.MOGUJIE_FOUR) > -1
                    || url.indexOf(InterceptUrl.MOGUJIE_FIVE) > -1 || url.indexOf(InterceptUrl.MOGUJIE_SIX) > -1
                    || url.indexOf(InterceptUrl.MEILISHUO_ONE) > -1 || url.indexOf(InterceptUrl.TAOBAO_THREE) > -1
                    ||url.indexOf(InterceptUrl.JD_THREE) > -1||url.indexOf(InterceptUrl.TAOBAO_EIGHT) > -1||
                    url.indexOf(InterceptUrl.PINDDD_ONE) > -1||url.indexOf(InterceptUrl.TAOBAO_SIX) > -1
                    ||url.indexOf(InterceptUrl.JD_FOUR) > -1 ||url.indexOf(InterceptUrl.TAOBAO_FIVE) > -1
                    ||url.indexOf(InterceptUrl.TAOBAO_SEVEN) > -1){
//                || url.indexOf(InterceptUrl.TAOBAO_FOUR) > -1
                if (url.indexOf(InterceptUrl.TAOBAO_FIVE) > -1) {

                        if (url.indexOf(InterceptUrl.TAOBAO_FOUR) > -1){
                            return true;
                        }

                    String remenUrl = "";
                    try {
                        remenUrl = URLDecoder.decode(url,"utf-8");
                        Log.e("dd==-=-=-=-=-=-",remenUrl);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    int indexStart = remenUrl.indexOf("&h5Url=");
                    String toStr = remenUrl.substring(indexStart+7);
                    Log.e("toStr",toStr);
                    interceptUrl(toStr);
                    return true;
                }else{
                    interceptUrl(url);
                }
                return true;
            }
            else{
                view.loadUrl(url);//每次发起新的请求，在新的WebView中打开
                return true;
            }

        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view,url,favicon);
//            dialog = ProgressDialog.show(WebViewActivity.this,null,"正在加载商品数据，请稍后..",true,true);
            view.getSettings().setBlockNetworkImage(true);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
//            dialog.dismiss();
            super.onPageFinished(view,url);
            view.getSettings().setBlockNetworkImage(false);
        }

        @Override
        public void onReceivedSslError(WebView view, final  SslErrorHandler handler, SslError error) {
            final AlertDialog.Builder builder = new AlertDialog.Builder
                    (WebViewActivity.this);
            builder.setMessage(R.string.sslerror_msg);
            builder.setPositiveButton("continue", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    handler.proceed();
                }
            });
            builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    handler.cancel();
                }
            });
            final AlertDialog dialog = builder.create();
            dialog.show();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.public_btn_left://返回
                finish();
                break;
        }
    }

    public boolean isTaobaoThree(String url) {
        boolean isOne = false;
        if (url.indexOf(InterceptUrl.TAOBAO_EIGHT) > -1 && url.indexOf("item_id") > -1&& url.indexOf("expo_id") > -1){
            isOne = true;
        }
        return isOne;
    }
}
